# -*- coding: UTF-8 -*-
import re
import requests
import traceback
import json
import urllib3
import os
import sys
import execjs
urllib3.disable_warnings()
import codecs

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
import ssl


class MyAdapter(HTTPAdapter):
    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(num_pools=connections,
                                       maxsize=maxsize,
                                       block=block,
                                       ssl_version=ssl.PROTOCOL_TLSv1)

# s = requests.session()
# s.cookies.clear()

# 禁用安全请求警告
# from requests.packages.urllib3.exceptions import InsecureRequestWarning
# requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


def get_request_encoding(response):
    encoding = "utf-8"
    try:
        encoding = response.encoding
        if encoding == 'ISO-8859-1':
            encodings = requests.utils.get_encodings_from_content(response.text)
            if encodings:
                encoding = encodings[0]
                if encoding == 'ISO-8859-1':
                    encoding = response.apparent_encoding  # 备用 时间慢
        if not encoding:  # api
            encoding = "utf-8"
    except:
        print(traceback.format_exc())
        encoding = "utf-8"
    finally:
        return encoding


def strToDic_WD(headerStr):
    rdict = dict()
    if headerStr.strip():
        for headItem in headerStr.split("\n"):
            parm = headItem.split(":", 1)  # 切分2
            if parm[0].strip():
                rdict[parm[0]] = headItem[(headItem.index(parm[0]) + parm[0].__len__() + 1):].strip()
            # rdict[parm[0].strip()] = parm[1].strip()
    return rdict


headers = {
            'Origin': 'https://www.sos.state.co.us',
           # 'Content-Length': '382',
           'Accept-Language': 'zh-CN,zh;q=0.9',
           'Accept-Encoding': 'gzip, deflate, br',
           'Upgrade-Insecure-Requests': '1',
           'Host': 'www.sos.state.co.us',
           'Referer': 'https://www.sos.state.co.us/biz/BusinessEntityCriteriaExt.do',
           'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
           # 'Cache-Control': 'max-age=0',
           'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
           'Content-Type': 'application/x-www-form-urlencoded'}


url = "https://www.sos.state.co.us/biz/BusinessEntityCriteriaExt.do"
res = requests.get(url, timeout=20, verify=False, headers={
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Accept-Encoding': 'gzip, deflate, br',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3887.7 Safari/537.36',
})
print(res.content.decode())

content = res.content.decode()

# print(content)
# sys.exit()

file_name = "colorado_origin.html"
with codecs.open(file_name, 'w', encoding="gb18030") as f:
    f.write(str(content))


def colorado_content_replace(content):
    # 取变量名 results.
    # oi(S, L(459), results.ol);
    f_name = content.split("(459),")[1].split(");")[0].replace("results.", "").strip()
    # f_name = re.findall(r';.*?\(S,.*?\(459\),.*?results\.(.*?)\);', content)[0]
    print("f_name", f_name)

    # 去 submit 整体
    il_head = content.split("results.{});".format(f_name))[1].split(")]()}}")[0]
    # il_head = content.split("p[JS_VAR.il]);")[1].split(")]()}}")[0]
    print("il_head", il_head)
    # )]()
    content = content.replace(il_head + ")]()", "")

    # set_timeouts = re.findall(r'setTimeout\((.*?),_', content)
    # setTimeout(FUNCS[FUNCS_ID],_(37)?1:0),FUNCS_ID++)
    # 去 setTimeout
    set_timeouts = re.findall(r',setTimeout\((.*?),FUNCS_ID', content)
    print(set_timeouts)

    function_name = set_timeouts[0].split(",")[0] + "()"
    print("function_name", function_name)

    replace_str = "setTimeout(" + set_timeouts[0]
    print("replace_str", replace_str)

    print("--"*20)
    content = content.replace(replace_str, function_name)

    w_inner_str = content.split("))}};")[1].split(";\nfunction")[0]
    print("w_inner_str", w_inner_str)

    # middle_listener = re.findall(r'window\["(.*?)"\]\?window', content)[0]
    # print("middle_listener", middle_listener)

    w_function_name = re.findall(r'\),(.*?),!1\):window\[', w_inner_str)[0] + "()"
    print("w_function_name", w_function_name)

    print("--"*20)

    content = content.replace(w_inner_str, w_function_name)
    return content, f_name


content, f_name = colorado_content_replace(content)
print(content)
# transfer_file = "colorado_transfer.html"
# with open(transfer_file, 'w') as f:
#     f.write(content)

# ----------------------
headers = {
          # 'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept-Encoding': 'gzip, deflate',
           'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3887.7 Safari/537.36',
            # "Content-Type": "application/x-www-form-urlencoded"
           }
# jsdom_api_url = "http://127.0.0.1:5592/api/colorado_get_param"
# url = "http://127.0.0.1:8081/api/colorado_get_param"
# jsdom_api_url = "http://172.16.30.34:5592/api/colorado_get_param"
jsdom_api_url = "http://61.155.157.2:5592/api/colorado_get_param"
body = {"html": content, "html_script": "window.ol = results.{};".format(f_name), "rlist": "['ol']"}
res = requests.post(jsdom_api_url, headers=headers, data=body, verify=False)
print(res.content)


# SI(S, O(459), results.jJ)
# zi(S, L(459), results.ol);